import { LayoutConsole,LayoutLarge } from '@/layouts/index'
import type {
    RouteLocationNormalized,
    RouteLocationNormalizedLoaded,
    NavigationGuardNext,
} from 'vue-router';


const path = import.meta.glob('@/views/**/index.tsx');
console.log(Object.entries(path));
export const routes = [
    {
        path: '/',
        name: 'root',
        redirect: { name: 'dashboard' },
        meta: {
            title: '根路由',
        },
    },
    {
        path: '/login',
        name: 'auth',
        component: LayoutLarge,
        redirect: { name: 'auth' },
        meta: {
            title: '授权',
        },
        children:[
            {
                path: 'login',
                name: 'login',
                component: () => import('@/views/login/index.tsx'),
                meta: {
                    title: '账号登录',
                },
            }
        ]
    },
    {
        path: '/console',
        name: 'console',
        component: LayoutConsole,
        redirect: { name: 'console-overview' },
        meta: {
            title: '控制台',
        },
        children: [
            {
                path: 'overview',
                name: 'console-overview',
                component: () => import('@/views/console/index.tsx'),
                meta: {
                    title: '总览',
                },
            },
            {
                path: 'struct',
                name: 'console-struct',
                component: () => import('@/views/struct/index.tsx'),
                meta: {
                    title: '结构',
                },
            },
            {
                path: 'dashboard',
                name: 'dashboard',
                component: () => import('@/views/dashboard/index.tsx'),
                meta: {
                    title: '仪表盘',
                },
            },
        ]
    },

    {
        path: '/:pathMatch(.*)*',
        name: 'not-found',
        component: () => import('@/views/errors'),
        meta: {
            title: '404',
        },
    },
];

export const middleware = (
    to: RouteLocationNormalized,
    from: RouteLocationNormalizedLoaded,
    next: NavigationGuardNext
) => {
    document.title = `${to.meta.title || ''} | 设备管理系统`;
    const permissions = localStorage.getItem('APP_PERMISSION') || sessionStorage.getItem('APP_PERMISSION')
    // 如果用户访问的是 '/login' 页面，直接放行
    if (to.name === 'login') {
        if (permissions !== null) {
            // 如果已有权限信息，跳转到主页或其他默认页面
            return next({ name: 'dashboard' })
        }
        return next() // 进入授权页面
    }
    // 如果没有权限且不是前往授权页面，则重定向到授权页面
    if (permissions === null) return next({ name: 'login',  query: { redirect: to.fullPath } })
    // 其他情况正常通行
    next();
};
